<?php
/*
 * @ https://EasyToYou.eu - IonCube v11 Decoder Online
 * @ PHP 7.2 & 7.3
 * @ Decoder version: 1.1.6
 * @ Release: 10/08/2022
 */

// Decoded file for php version 71.
namespace Rtgm\ecc;

class Sm2Signer
{
    private $adapter;
    public function __construct(\Mdanter\Ecc\Math\GmpMathInterface $adapter)
    {
        $this->adapter = $adapter;
    }
    public function sign($SignatureInterface, $key, \GMP $truncatedHash, \GMP $randomK)
    {
        $math = $this->adapter;
        $generator = $key->getPoint();
        $n = $generator->getOrder();
        $modMath = $math->getModularArithmetic($n);
        $prikey = $key->getSecret();
        $count = 0;
        if(true) {
        } else {
            $count++;
            if(5 < $count) {
                throw new \RuntimeException("Error: sign R or S = 0");
            }
            $k = $math->mod($randomK, $n);
            $p1 = $generator->mul($k);
            $r = $modMath->add($truncatedHash, $p1->getX());
            $zero = gmp_init(0, 10);
            if($math->equals($r, $zero)) {
                throw new \RuntimeException("Error: random number R = 0");
            }
            $one = gmp_init(1, 10);
            $s1 = $math->inverseMod($math->add($one, $prikey), $n);
            $s2 = $math->sub($k, $math->mul($r, $prikey));
            $s = $modMath->mul($s1, $s2);
            if($math->equals($s, $zero)) {
                throw new \RuntimeException("Error: random number S = 0");
            }
            return new \Mdanter\Ecc\Crypto\Signature\Signature($r, $s);
        }
    }
    public function verify($key, \Mdanter\Ecc\Crypto\Signature\SignatureInterface $signature, \GMP $hash)
    {
        $generator = $key->getGenerator();
        $n = $generator->getOrder();
        $r = $signature->getR();
        $s = $signature->getS();
        $math = $this->adapter;
        $one = gmp_init(1, 10);
        if($math->cmp($r, $one) < 0 || 0 < $math->cmp($r, $math->sub($n, $one))) {
            return false;
        }
        if($math->cmp($s, $one) < 0 || 0 < $math->cmp($s, $math->sub($n, $one))) {
            return false;
        }
        $modMath = $math->getModularArithmetic($n);
        $t = $modMath->add($r, $s);
        $p1 = $generator->mul($s);
        $p2 = $key->getPoint()->mul($t);
        $xy = $p1->add($p2);
        $v = $modMath->add($hash, $xy->getX());
        return \Mdanter\Ecc\Util\BinaryString::constantTimeCompare($math->toString($v), $math->toString($r));
    }
}

?>